package main

import (
	"log"
	"time"
)

type subject struct {
	observers map[int]chan string
	num       int
}

func newSubject() *subject {
	return &subject{
		num:       0,
		observers: make(map[int]chan string),
	}
}

func (s *subject) register(c chan string) int {
	s.num++
	n := s.num
	s.observers[n] = c

	return n
}

// Deregister 取消.
func (s *subject) Deregister(num int) {
	delete(s.observers, num)
}

func (s *subject) notify(str string) {
	for _, c := range s.observers {
		go func(ch chan string, s string) {
			ch <- s
		}(c, str)
	}
}

func run() chan string {
	c := make(chan string)
	go func(ch chan string) {
		for {
			log.Println(<-ch)
		}
	}(c)

	return c
}

func run2() chan string {
	c := make(chan string)

	return c
}

func main() {
	log.Println("开始")

	s := newSubject()
	a := s.register(run())
	b := s.register(run2())
	log.Printf("%d, %d", a, b)

	for i := 0; i < 10; i++ {
		s.notify("你好")
	}

	time.Sleep(time.Second)
	// s.deregister(a)
	for i := 0; i < 10; i++ {
		s.notify("吃饭")
	}

	time.Sleep(time.Second)
}
